import 'package:dio/dio.dart';
import 'package:honeypotflutter/modules/autonym/model/autonym_oss_model.dart';
import 'package:honeypotflutter/net/public_http.dart';
import 'package:honeypotflutter/public/public_total.dart';
import 'package:image_picker/image_picker.dart';

class MGBussineOSS {
  /*
  * 上传图片
  * */
  static Future<String> uploadImage(XFile file) async {
    try {
      HLTotal.progress(status: "图片上传中...");
      Map param = {"fileName": "idcard/{yyyy}/{MM}/{dd}/{guid}.png"};
      Map<String, dynamic> ossInfo = await MGHttp.post("api/Oss/Sign", params: param);
      AutonymOssModel ossModel = AutonymOssModel.fromJson(ossInfo);
      await _upLoadOssImage(ossModel, file);
      return ossModel.host! + ossModel.key!;
    } catch (error) {
      HLTotal.dismiss();
      return Future.error(error);
    }
  }

  /*
  * 上传图片
  * */
  static Future<bool> _upLoadOssImage(AutonymOssModel ossModel, XFile file) async {
    MultipartFile fromFile = await MultipartFile.fromFile(file.path, filename: ossModel.key!);
    var formData = FormData.fromMap({
      "file": fromFile,
      "key": ossModel.key,
      "policy": ossModel.policy,
      "OSSAccessKeyId": ossModel.ossAccessKeyId,
      "success_action_status": ossModel.successActionStatus,
      "signature": ossModel.signature,
      "callback": ossModel.callback,
    });
    try {
      var result = await Dio().postUri(Uri.parse(ossModel.host!),
          data: formData,
          options: Options(
            contentType: "multipart/form-data",
          ));
      return true;
    } catch (error) {
      HLTotal.total("OSS上传失败");
      return Future.error(error);
    } finally {
      HLTotal.dismiss();
    }
  }
}
